package com.wing.order.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.entity.CellInventoryInout;
import com.wing.cabinet.model.entity.CellInventoryInoutDetail;
import com.wing.cabinet.model.entity.StorageInventoryInout;
import com.wing.cabinet.model.response.CabinetVO;
import com.wing.cabinet.model.response.CellInventoryInoutVO;
import com.wing.cabinet.model.response.StorageInventoryInoutVO;
import com.wing.cabinet.service.CabinetService;
import com.wing.cabinet.service.CellInventoryInoutDetailService;
import com.wing.cabinet.service.CellInventoryInoutService;
import com.wing.cabinet.service.StorageInventoryInoutService;
import com.wing.cabinet.utils.ExcelUtils;
import com.wing.order.model.entity.OrderReceiveLoad;
import com.wing.order.model.request.OrderReceiveLoadForm;
import com.wing.order.model.response.OldNewOrderVO;
import com.wing.order.model.response.OrderReceiveLoadVO;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.DepartmentVO;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.order.model.entity.OldNewOrder;
import com.wing.order.model.request.OldNewOrderForm;
import com.wing.order.service.OldNewOrderService;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-以旧换新(存旧刀，领新刀)管理", tags = "#/order/oldNewOrder")
@RestController("oldNewOrderController")
@RequestMapping("order/admin/oldNewOrder")
@RequiredArgsConstructor
@Slf4j
public class OldNewOrderController {

    private final OldNewOrderService oldNewOrderService;
    private final CellInventoryInoutService cellInventoryInoutService;
    private final CellInventoryInoutDetailService cellInventoryInoutDetailService;
    private final CabinetService cabinetService;
    private final StorageInventoryInoutService storageInventoryInoutService;
    @Autowired
    private UserClient userClient;
    @ApiOperation(value = "查询所有以旧换新(存旧刀，领新刀)", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "desc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<OldNewOrderVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,Long id
            ,String code
            ,String deviceCode
            ,String skuCode
            ,String startTime
            ,String endTime
            ,Long creatorId
            ,Long departmentId
    ){

        Page<OldNewOrderVO> pg = new Page<>(page, limit);



        Map<String,Object> params = new HashMap<>();
        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        //搜索
        if (StringUtils.isNotBlank(code)){
            params.put("code",code);
        }
        if (StringUtils.isNotBlank(deviceCode)){
            params.put("deviceCode",deviceCode);
        }
        if (StringUtils.isNotBlank(skuCode)){
            params.put("skuCode",skuCode);
        }
        if (id!=null){
            params.put("id",id);
        }
        if (creatorId!=null){
            params.put("creatorId",creatorId);
        }
        if (departmentId!=null&&creatorId==null){
            params.put("departmentId",departmentId);
        }
        params.put("startCreateTime",startTime);
        params.put("endCreateTime",endTime);
        params.put("enterpriseCode", JwtUtils.getEnterpriseCode());
        Page<OldNewOrderVO> list = oldNewOrderService.pageList4app(pg,params);
       /* IPage<OldNewOrder> list = oldNewOrderService.getBaseMapper().selectPage(pg, queryWrapper);
        for (int i = 0; i < list.getRecords().size(); i++) {
            System.out.println(list.getRecords().get(i).getOldCellInventoryInoutId());
            CellInventoryInoutVO cellInventoryInoutVO =  cellInventoryInoutService.get4appById(list.getRecords().get(i).getOldCellInventoryInoutId());//之前领新单id(关联cab_cell_inventory_inout表的id)
            if (cellInventoryInoutVO!=null){
                list.getRecords().get(i).setOldLeadNewCode(cellInventoryInoutVO.getCode());//旧的领新编号
                list.getRecords().get(i).setOldLeadNewCab(cellInventoryInoutVO.getCabCode());//旧的领新所属刀柜
            }
            StorageInventoryInoutVO storageInventoryInoutVO =  storageInventoryInoutService.get4appById(list.getRecords().get(i).getStorageInventoryInoutId());//暂存库存入的id关联cab_storage_inventory_inout
            list.getRecords().get(i).setStorageCode(storageInventoryInoutVO.getCode());//暂存订单编号
            list.getRecords().get(i).setStorageSeat(storageInventoryInoutVO.getCabCode()+"-"+storageInventoryInoutVO.getSpaceCode());//存刀订单库位信息 暂存订单柜子编号 暂存订单货道编号
            list.getRecords().get(i).setStorageStatus(storageInventoryInoutVO.getStatus().getDesc());//暂存订单状态

            CellInventoryInoutVO cellInventoryInoutVO1 =  cellInventoryInoutService.get4appById(list.getRecords().get(i).getNewCellInventoryInoutId());//新的领新的订单id
            list.getRecords().get(i).setNewLeadNewCode(cellInventoryInoutVO1.getCode());//新的领新编号
            list.getRecords().get(i).setNewLeadNewStatus(cellInventoryInoutVO1.getStatus().toString());//新的领新状态
            list.getRecords().get(i).setNewLeadNewSpaceCode(cellInventoryInoutVO1.getCabCode()+"-"+cellInventoryInoutVO1.getSpaceCode());//新的领新货道编号
        }*/
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    //旧
    @GetMapping("/oldLeadNewList")
    public JsonResult getOldLeadNewList(@RequestParam("id") Long id,@RequestParam("skuCode") String skuCode){
        CellInventoryInoutVO cellInventoryInoutVO = cellInventoryInoutService.get4appByInOutIdAndSkuCode(id,skuCode);
        if(cellInventoryInoutVO==null){
            return JsonResult.fail("查询失败");
        }
        return JsonResult.success("查询成功",cellInventoryInoutVO);
    }

    //存
    @GetMapping("/storageList")
    public JsonResult getStorageList(@RequestParam("id") Long id,@RequestParam("skuCode") String skuCode){
        StorageInventoryInoutVO storageInventoryInoutVO =  storageInventoryInoutService.get4appByInOutIdAndSkuCode(id,skuCode);
        if(storageInventoryInoutVO==null){
            return JsonResult.fail("查询失败");
        }
        return JsonResult.success("查询成功",storageInventoryInoutVO);
    }

    //新
    @GetMapping("/newLeadNewList")
    public JsonResult getNewLeadNewList(@RequestParam("id") Long id,@RequestParam("skuCode") String skuCode){
        CellInventoryInoutVO cellInventoryInoutVO = cellInventoryInoutService.get4appByInOutIdAndSkuCode(id,skuCode);
        if(cellInventoryInoutVO==null){
            return JsonResult.fail("查询失败");
        }
        return JsonResult.success("查询成功",cellInventoryInoutVO);
    }



    @ApiOperation(value = "添加以旧换新(存旧刀，领新刀)", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(OldNewOrderForm.Add.class) OldNewOrderForm oldNewOrderForm) {
        if (oldNewOrderService.add(oldNewOrderForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改以旧换新(存旧刀，领新刀)", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(OldNewOrderForm.Update.class) OldNewOrderForm oldNewOrderForm) {
        OldNewOrder oldNewOrder = oldNewOrderService.getById(oldNewOrderForm.getId());
        if(oldNewOrder == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(OldNewOrder.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(oldNewOrderForm, oldNewOrder, copyOptions);
        if (oldNewOrderService.updateById(oldNewOrder)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



@ApiOperation(value = "删除以旧换新(存旧刀，领新刀)", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldNewOrderId", value = "以旧换新(存旧刀，领新刀)id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long oldNewOrderId) {
        if (oldNewOrderService.removeById(oldNewOrderId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "导出以旧换新记录")
    @GetMapping("/export")
    public void export(HttpServletResponse response, String startCreateTime, String endCreateTime,String enterpriseCode){
        List<OldNewOrderVO> oldNewOrderVOList = new ArrayList<>();
        if ("".equals(startCreateTime) || "".equals(endCreateTime)){
            log.error("上货时间为空："+startCreateTime);
        }
        endCreateTime = endCreateTime+" 23:59:59";
        Map paramsMap = new HashMap();
        paramsMap.put("startCreateTime",startCreateTime);
        paramsMap.put("endCreateTime",endCreateTime);
        paramsMap.put("enterpriseCode",enterpriseCode);
        oldNewOrderVOList = oldNewOrderService.list4app(paramsMap);
        for(OldNewOrderVO item : oldNewOrderVOList){
            JsonResult<DepartmentVO> jsonResult = userClient.getDepartmentVOById(item.getDepartmentId());
            item.setCostCenter(jsonResult.getData().getCostCenter());
        }

        //导出
        ExcelUtils.export(response,"以旧换新记录",oldNewOrderVOList, OldNewOrderVO.class);
    }
}
